import crypto from 'crypto';
import crypt3 from './crypt3';

/**
 * addUser - Generate a htpasswd format for .htpasswd
 * @param {string} user
 * @param {string} passwd
 * @returns {string}
 */
export default function addUser(
    user: string,
    passwd: string,
): string {
    if (!user || !passwd) {
        throw new Error('user and password is required');
    }

    if (user !== encodeURIComponent(user)) {
        throw new Error('username should not contain non-uri-safe characters');
    }

    if (crypt3) {
        passwd = crypt3(passwd);
    } else {
        passwd =
            '{SHA}' +
            crypto
                .createHash('sha1')
                .update(passwd, 'utf8')
                .digest('base64');
    }
    const comment = 'autocreated ' + new Date().toJSON();
    return `${user}:${passwd}:${comment}`;
}
